// import fetch from 'isomorphic-fetch'

import 'whatwg-fetch';
import * as types from './ActionTypes';
import 'es6-promise';
import {hashHistory} from 'react-router'

//获取用户登录状态和用户id
export const user_logined = (type,userId,userTel) =>{
  return dispatch=>dispatch({type:types.USER_LOGINED,getData:type,userId:userId||0,userTel:userTel})
}

export const testApiUrl = 'https://api.meirenguvip.com';
// let testApiUrl = 'http://120.27.37.54';

export const checkArr = (arr)=>{
  return dispatch=>dispatch({type:types.CHECKED_ARR,getData:arr})
}


/**
 * get请求
 * @param  {String} options.url   api地址
 * @param  {String} options.query query参数
 * @return {Promise}               Promise
 */
const _get = ({ url, query },dispatch) => {
  dispatch({type:types.START_LOADING})
  let _url
  if (query) {
    _url = `${testApiUrl}${url}?${query}`
  } else {
    _url = `${testApiUrl}${url}`
  }
  console.log(_url)
  return fetch(_url,{
        method: 'GET',
        mode: 'cors',
        cache: 'default'
      })
    .then(res => {
      dispatch({type:types.FINISH_LOADING})
      if (res.status >= 200 && res.status < 300) {
        return res.json()
      }
      return Promise.reject(new Error(res.status));
    })
}

// 查询项目分类
export const itemClass_show = () => {
 const url = '/mb/itemClass/show';
 return (dispatch) =>{
   _get({url},dispatch)
     .then((json) => {
       if(json.msg === '操作成功'){
         dispatch({type:types.ITEMCLASS_SHOW, getData:json.data.list})
       }
       // return Promise.reject(new Error('fetch fail'))
     })
     .catch((error) => {
       // dispatch({type:types.FETCH_COMING_SOON_FAIL})
       return Promise.reject(error)
     })
 }
}

/**
 * 获取首页信息
 * @param  {Function} options.dispatch store对象解构出来的函数，无需手动提供
 * @param  {Number} page             页数
 * @param  {Number} count             每页数量
 * @return {Promise}                  Promise
 */
 export const index_data = (page,count) => {
  const url = '/index';
  return (dispatch) =>{
    _get({url},dispatch)
      .then((json) => {
        if(json.status === 'ok'){
          dispatch({type:types.FETCH_INDEX_DATA, index_data:json})
        }
        // return Promise.reject(new Error('fetch fail'))
      })
      .catch((error) => {
        // dispatch({type:types.FETCH_COMING_SOON_FAIL})
        return Promise.reject(error)
      })
  }
}

//资讯分类列表接口
export const news_cms_class_list = () => {
  var timestamp=new Date().getTime(),
      key = fa91324aa01923e7c7f7ee1c3e45d6b0,
      stringSignTemp = '',
      sign = '';
      const query = ``;
  return (dispatch)=>{
    fetch(testApiUrl + "/news_cms/class/list", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: query
    }).then(function(res) {
      if (res.ok) {
        console.log("success");
        return res.json();
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    }).then(function(res){
      // console.log(res.data.list)
      dispatch({type:types.NEWS_CMS_CLASS_LIST, getData:res.data.list})
    });
  }
}
//资讯文章列表
export const news_cms_art_list = (acId) => {
  const query = (acId)?'ac_id='+acId:'';
  return (dispatch)=>{
    fetch(testApiUrl + "/news_cms/article/list", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: query
    }).then(function(res) {
      if (res.ok) {
        console.log("success");
        return res.json();
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    }).then(function(res){
      dispatch({type:types.NEWS_CMS_ART_LIST, getData:res.data.list})
    });
  }
}



/**
 *   them_hos_data
 * @param  {Function} options.dispatch store对象解构出来的函数，无需手动提供
 * @param  {Number} page             页数
 * @param  {Number} count             每页数量
 * @return {Promise}                  Promise
 */
 // 甄选 - > 医院列表
 export const them_hos_data = (page,count) => {
  const url = '/mb/hospital';
  const query = `pageSize=${page}&pageNo=${count}`
  return (dispatch) =>{
    _get({url,query},dispatch)
      .then((json) => {
        if(json.msg === '操作成功'){
          dispatch({type:types.FETCH_MALL_THEM_HOS, getData:json})
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
}
 // 甄选 - > 医院列表 ->医院详情
export const mall_them_hos_det = (hospitalId) => {
 const url = '/mb/hospital/show';
 const query = `hospitalId=${hospitalId}`
 return (dispatch) =>{
   _get({url,query},dispatch)
     .then((json) => {
       if(json.msg === '操作成功'){
         dispatch({type:types.FETCH_MALL_THEM_HOS_DET, getData:json.data.list})
       }
     })
     .catch((error) => {
       return Promise.reject(error)
     })
 }
}
// 甄选 - > 医院列表 ->医院详情 ->服务项目
export const mall_them_hos_servItem = (obj) => {
  const url = '/mb/itemPro/show';
  let query = '';
  if(obj){
    for(let i in obj){
      query += i + '=' +obj[i] + '&'
    }
  }
  return (dispatch) =>{
    _get({url,query},dispatch)
      .then((json) => {
        if(json.code === '40300'){
          dispatch({type:types.FETCH_MALL_THEM_HOS_SERVITEM, getData:json.data.list})
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
    }
}
// 医院列表 ->医院详情 ->医生信息
export const mall_them_doc_show = (hospitalId) => {
  const url = '/mb/doctor/show';
  const query = `hospitalId=${hospitalId}`
  return (dispatch) =>{
    _get({url,query},dispatch)
      .then((json) => {
        console.log(json);
        if(json.msg === '操作成功'){
          dispatch({type:types.FETCH_MALL_THEM_DOC_SHOW, getData:json.data.list})
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
}
// 甄选 - > 医院列表 ->医院详情 ->服务项目-详情
export const mall_them_hos_servItem_det = (itemId) => {
  const url = '/mb/itemPro/detail';
  const query = `itemId=${itemId}`
  return (dispatch) =>{
    _get({url,query},dispatch)
      .then((json) => {
        if(json.msg === '操作成功'){
          dispatch({type:types.FETCH_MALL_THEM_HOS_SERVITEM_DET, getData:json.data})
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
    }
}
//pageSize 多少条
//pageno 多少页
// 甄选 - > 医生列表
export const them_doc_data = (page,count) => {
 const url = '/mb/doctor';
 const query = `pageSize=${page}&pageNo=${count}`
 return (dispatch) =>{
   _get({url,query},dispatch)
     .then((json) => {
       if(json.code === '40300'){
         console.log(json);
         dispatch({type:types.FETCH_MALL_THEM_DOC, getData:json.data.list})
       }
     })
     .catch((error) => {
       return Promise.reject(error)
     })
 }
}
// 甄选 - > 医生列表 -> 医生详情
export const mall_them_doc_det = (doctorId) => {
  const url = '/mb/doctor/detail';
  const query = `doctorId=${doctorId}`
  return (dispatch) =>{
    _get({url,query},dispatch)
      .then((json) => {
        console.log(json);
        if(json.code === '40300'){
          dispatch({type:types.FETCH_MALL_THEM_DOC_DET, getData:json.data.list})
        }else{
          alert(json.msg)
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
}

// 查询项目详情里面的   相关案例
export const servItem_caseList = (itemId) => {
  const url = '/mall/case';
  const query = `item_id=${itemId}`
  return (dispatch) =>{
    _get({url,query},dispatch)
      .then((json) => {
        if(json.code == '200'){
          dispatch({type:types.FETCH_MALL_THEM_ANLI, getData:json.data.list})
        }else{
          dispatch({type:types.FETCH_MALL_THEM_ANLI, getData:[]})
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
}

export const itemPro = ()=>{
  const url = '/mb/itemPro';
  return (dispatch) => {
    _get({url},dispatch)
    .then((json) => {
      if(json.msg === '操作成功'){

        dispatch({type:types.ITEM_PRO, getData:json.data.list})
      }
    })
    .catch((error) => {
      return Promise.reject(error)
    })
  }
}
// 生成订单
// http://120.27.37.54/mall/order/gen?param={"user_phone": 15011095069,"cart_list":
// [{"cart_id": 0,"user_id": 1,"item_price": 2380,"item_num": 3,"item_id": 2,"hospital_id": 49,"doctor_id": 10,
// "item_name": "爱芙莱玻尿酸（0.5ML/次）","order_from": 1,"item_image": "148456874754.jpg"}
export const pro_order_list = (user_phone,myconfig) => {
  let param = {
    "user_phone":user_phone,
    "cart_list":myconfig
  };
  console.log(param)
  fetch(testApiUrl + "/mall/order/gen", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      body: "param="+JSON.stringify(param)
    }).then(function(res) {
      console.log(res);
      console.log("param="+JSON.stringify(param))
      if (res.ok) {
        return res.json();
        console.log("success");
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    }).then(function(res){
      hashHistory.push('/user/pay/'+res.data.unionSN)
    });
}

//加入购物车
export const add_shopcar = (userId,hospitalId,itemId,itemNum) => {
  const query = `user_id=${userId}&hospital_id=${hospitalId}&item_id=${itemId}&item_num=${itemNum}`
    fetch(testApiUrl + "/mall/cart/add", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: query
    }).then(function(res) {
      if (res.ok) {
        console.log("success");
        return res.json();
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    });
}

//获取 or 更新用户购物车中未支付的物品
export const get_add_shopcar = (userId,callback) => {
  const query = `user_id=${userId}`;
  return (dispatch) => {
    fetch(testApiUrl + "/mall/cart/list", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: query
    }).then(function(res) {
      if (res.ok) {
        console.log("success");
        return res.json();
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    }).then(function(res){
      dispatch({type:types.USER_SHOP_LIST, getData:res.data});
      if(callback){
        callback();
      }
    });
  }
}

//获取用户购物车中未支付的物品
export const dele_shop_order = (cart_id,callBack) => {
  const query = cart_id;
  return (dispatch) => {
    fetch(testApiUrl + "/mall/cart/"+query, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/form-data"
      },
      body: ''
    }).then(function(res) {
      if (res.ok) {
        console.log("删除成功");
        return res.json();
      } else if (res.status == 401) {
        console.log("Oops! You are not authorized.");
      }
    }, function(e) {
      console.log("Error submitting form!");
    }).then(function(res){
      if(callBack)callBack(res);
    });
  }
}

//分页获取或更新订单列表
export const order_detail = (obj) => {
  let query = '';
  for (let i in obj) {
    query += `${i}=${obj[i]}&`
  }
  console.log(query);
  return (dispatch)=>{
    dispatch({type:types.START_LOADING})
    fetch(testApiUrl + "/mall/order/detail", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: query
    }).then(function(res) {
      if (res.ok) {
        return res.json();
      }else{
        console.log("服务器开小差了");
        return false;
      }
    }, function(e) {
      console.log("Error submitting form!");
    })
    .then(function(res){
      let data_det = !!res.data?res.data:[];
      dispatch({type:types.GET_ORDER_DETAIL, getData:data_det})
      dispatch({type:types.FINISH_LOADING})
    });
  }
}

//分页获取或更新订单列表
export const get_order_classify = (obj) => {
  let query = '';
  for (let i in obj) {
    query += `${i}=${obj[i]}&`
  }
  console.log(query);
  return (dispatch)=>{
    dispatch({type:types.START_LOADING})
    fetch(testApiUrl + "/mall/order/list", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: query
    }).then(function(res) {
      if (res.ok) {
        return res.json();
      } else{
        console.log("服务器开小差了");
      }
    }, function(e) {
      console.log("Error submitting form!");
    })
    .then(function(res){
      let data_list = !!res.data?res.data.list:[];
      dispatch({type:types.GET_ORDER_CLASSIFY, getData:data_list})
      dispatch({type:types.FINISH_LOADING})
    });
  }
}


//分页获取或更新订单列表  加载更多
export const get_order_classify_more = (obj,callBack) => {
  let query = '';
  for (let i in obj) {
    query += `${i}=${obj[i]}&`
  }
  console.log(query);
  return (dispatch)=>{
    dispatch({type:types.START_LOADING})
    fetch(testApiUrl + "/mall/order/list", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: query
    }).then(function(res) {
      console.log(res)
      if (res.ok) {
        console.log("success");
        return res.json();
      }else{
        console.log("服务器开小差了");
      }
    }, function(e) {
      console.log("Error submitting form!");
    }).then(function(res){
      if(res.code == '200'){
        let data_list = !!res.data?res.data.list:[];
        dispatch({type:types.GET_ORDER_CLASSIFY_MORE, getData:data_list})
      }else{
        if(callBack)callBack(res)
      }
      dispatch({type:types.FINISH_LOADING})
    });
  }
}


// 支付系列
function getcookie(name){
    var strcookie=document.cookie;
    var arrcookie=strcookie.split("; ");
    for(var i=0;i<arrcookie.length;i++){
        var arr=arrcookie[i].split("=");
        if(arr[0]==name)return decodeURIComponent(arr[1]); //增加对特殊字符的解析
    }
    return "";
}

function delCookie(name){
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getcookie(name);
    if(cval!=null) document.cookie= name + "="+cval+"; path=/;expires="+exp.toGMTString();
}

export const pay_set = () => {
        var url_ = encodeURIComponent(window.location.href);
        $.ajax({
            type : "get",
            async : false,
            url : testApiUrl + "/wxcs/service/config?url="+url_,
            dataType: "jsonp",
            jsonp: "jsonpCallback",
            jsonpCallback:"success_jsonpCallback",
            success : function(json) {
                console.log("json: a a a "+JSON.stringify(json));
                wx.config({
                    debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId : "wx22ae3075d64a4f81", // 必填，公众号的唯一标识
                    timestamp : json.timestamp, // 必填，生成签名的时间戳
                    nonceStr : json.noncestr, // 必填，生成签名的随机串
                    signature : json.signature,// 必填，签名
                    jsApiList: ['checkJsApi','openLocation','getLocation','chooseWXPay']// 必填，需要使用的JS接口列表
                });
            }
        });
    }



export const jsApiCall = (item,user) =>{
     var openid=getcookie('wxopenid');
     console.log(item);
     console.log(user);
     let query = {
       item_id:item.itemId, hospital_id:item.hospitalId,
       user_id:user.userId, user_phone:user.userTel, doctor_id:item.doctorId,
     }
     console.log(JSON.stringify(query));
    $.ajax({
        type:'POST',
        url:testApiUrl + '/payment/wx/unifiedorder',
        //url:'http://localhost:8080/wx/unifiedorder',
        async:false,
        cache:false,
        contentType:"application/x-www-form-urlencoded; charset=utf-8",
        data:{body:item.itemName,out_trade_no:item.unionSN, total_fee:1,
            trade_type:'JSAPI', device_info:'WEB', openid:openid,
            attach:JSON.stringify(query)},
        //dataType:'jsonp',
        success: function (result){
          console.log(result);
            if (result!=null){
                //调起微信支付
                wx.chooseWXPay({
                    timestamp: result.data.jsPayParams.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: result.data.jsPayParams.nonceStr, // 支付签名随机串，不长于 32 位
                    package: result.data.jsPayParams.packages, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    signType: result.data.jsPayParams.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: result.data.jsPayParams.paySign, // 支付签名
                    error:function(){
                        setTimeout(function(){hashHistory.push('/user/payStatus/fail')},400)
                    },
                    success: function (res) {
                        // 支付成功后的回调函数
                        // alert('付成功后的回调函数' + JSON.stringify(res));
                        setTimeout(function(){hashHistory.push('/user/payStatus/' + item.unionSN)},400)

                    }
                });
            }else {
              setTimeout(function(){hashHistory.push('/user/payStatus/fail')},400)
            }
        },
        error: function(e) {
            setTimeout(function(){hashHistory.push('/user/payStatus/fail')},400)
        }
    })
}

//申请退款
export const apply_refund = (query,itemPrice) => {
  console.log(query);
  console.log(itemPrice);
  fetch(testApiUrl + "/mall/order/refund_apply", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
    },
    body: query
  }).then(function(res) {
    if (res.ok) {
      return res.json();
    } else if (res.status == 401) {
      console.log("Oops! You are not authorized.");
    }
  }, function(e) {
    console.log("Error submitting form!");
  }).then(function(res){
    console.log(res);
      if(res.code == 200){
        console.log(itemPrice);
        hashHistory.push('/user/applyRefundStatus/' +itemPrice)
      }else {
        alert(res.msg)
        hashHistory.push('/userView/user')
      }

  })
}


export const check_code = (query,callBack) => {
  fetch(testApiUrl + "/uc/check_code", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: query
  }).then(function(res){
    console.log("/uc/check_code" + query)
    if (res.ok) {
      return res.json();
    } else{
      console.log("服务器开小差了");
    }
  }, function(e) {
    console.log("Error submitting form!");
  }).then(function(res){
    console.log(res)
    if(callBack)callBack(res)

  })
}


export const user_login = (query,callBack) => {
  fetch(testApiUrl + "/uc/login", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: query
  }).then(function(res){
    if (res.ok) {
      return res.json();
    }else{
      $('.userLogin .err_msg').empty().text('* 服务器开小差了')
    }
  }, function(e) {
    console.log("Error submitting form!");
  }).then(function(res){
    if(callBack)callBack(res)
  })
}
